<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\BaseController;
use App\Http\Events\Admin\AdminEvent;
use App\Http\Model\Admin\Source;
use App\Http\Model\Admin\Tourist;
use App\Http\Model\Admin\TouristAction;
use App\Http\Model\Admin\TouristInfo;
use App\Http\Model\Admin\TouristProfile;
use Config;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Route;
use Webpatser\Uuid\Uuid;

class TouristController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $s_d = new Tourist();
        $query = $request->query();
        $tourists_data = $s_d->findAllByPaginate(15, $query);
        if (count($tourists_data)) {
            foreach ($tourists_data as $key => $item) {
                $tourists_data[$key]['tourist_info'] = $item->touristInfo;
            }
        }
        $source = new Source();
        $source_list = $source->findAll();
//        return $tourists_data;
        return view('admin.tourist', [
            'tourists_list' => $tourists_data,
            'city_list' => Config::get('admin.cities'),
            'status_list' => config::get('admin.status'),
            'source_list' => $source_list,
            'query' => $query,
            'current_url' => $request->getPathInfo()
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $from = $_SERVER['HTTP_REFERER'];
        $t = new Tourist();
        $one = $t->findOneById($id);
        $source = new Source();
        $source_list = $source->findAllByPaginate(1000);
        $action_ins = new TouristAction();
        $action_ins->setTable('tourists_actions'.$this->getTableNum($one['phone']));
        $tourist_action_list = $action_ins->findListById($id);
        $one['tourist_info'] = (new TouristInfo())->findOneByPhone($one['phone']);
        $tourist_action_list_diy = [];
        $tourist_action_list_original = [];
        if (count($tourist_action_list)) {
            foreach ($tourist_action_list as $item) {
                $item['data_input'] == 2 ? array_push($tourist_action_list_diy, $item) : array_push($tourist_action_list_original, $item);
            }
        }
        return view('admin.tourist_info', [
            'tourist' => $one,
            'source_list' => $source_list,
            'tourist_action_list_original' => $tourist_action_list_original,
            'tourist_action_list_diy' => $tourist_action_list_diy,
            'city_list' => Config::get('admin.cities'),
            'status_list' => config::get('admin.status'),
            'purpose_list' => config::get('admin.purpose'),
            'use_list' => config::get('admin.use'),
            'success' => '',
            'referer' => $from
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $user = new Tourist();
        $one = $user->findOneById($id);
        return view('admin.tourist_edit', ['tourist_info' => $one]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $referer = Input::all()['_referer'];
        $input = Input::except('_token', '_method','_referer');
        $validator = $this->formValidator($input,Config::get('admin.tourist.rules'), Config::get('admin.tourist.message'));
        if($validator->passes()) {
            $old_data = (new Tourist())->findOneById($id)->toArray();
            $tourist_input = [
                'id' => $id,
                'city' => $input['city'],
                'source_id' => $input['source_id'],
                'name' => $input['name'],
                'status' => intval($input['status']),
                'purpose' => intval($input['purpose']),
                'use' => intval($input['use']),
                'remark' => $input['remark'],
                'admin_id' => session('dmp_user')['id'],
                'admin_name' => session('dmp_user')['name']
            ];
            $tourist_info_input = [
                'name' => $input['name'],
                'remark' => $input['remark'],
                'city' => $input['city'],
                'district' => $input['district'],
                'district_ids' => $input['district_ids'],
                'business_area' => $input['business_area'],
                'business_area_ids' => $input['business_area_ids'],
                'price' => $input['price'] ? $input['price'] : 0,
                'area' => $input['area'] ? $input['area'] : 0,
                'house_room' => $input['house_room'] ? $input['house_room'] : 0,
            ];
            $borough_arr = $input['district'] ? explode(',', $input['district']) : [];
            $borough_id_arr = $input['district_ids'] ? explode(',', $input['district_ids']) : [];
            $cityarea2_arr = $input['business_area'] ? explode(',', $input['business_area']) : [];
            $cityarea2_id_arr = $input['business_area_ids'] ? explode(',', $input['business_area_ids']) : [];
            $tourist_action_input = [];
            if (count($borough_arr) && count($cityarea2_arr)) {
                foreach ($borough_arr as $key => $item) {
                    $aa = [
                        'user_id' => $id,
                        'id' => '',
                        'data_input' => 2,
                        'house_city' => $input['city'],
                        'phone' => $input['phone'],
                        'appName' => $input['appName'],
                        'house_price' => $input['price'] ? $input['price'] : 0,
                        'house_room' => $input['house_room'] ? $input['house_room'] : 0,
                        'house_totalarea' => $input['area'] ? $input['area'] : 0,
                        'house_city' => $input['city'],
                        'borough_name' => $item,
                        'borough_id' => $borough_id_arr[$key],
                        'cityarea2_name' => '',
                        'cityarea2_id' => 0,
                        'admin_id' => session('dmp_user')['id'],
                        'admin_name' => session('dmp_user')['name']
                    ];
                    foreach ($cityarea2_arr as $k => $c) {
                        $aa['id'] = Uuid::generate()->string;
                        $aa['cityarea2_name'] = $c;
                        $aa['cityarea2_id'] = $cityarea2_id_arr[$k];
                        array_push($tourist_action_input, $aa);
                    }
                }
            } else {
                if (count($borough_arr)) {
                    foreach ($borough_arr as $key => $item) {
                        $aa = [
                            'user_id' => $id,
                            'id' => Uuid::generate()->string,
                            'data_input' => 2,
                            'house_city' => $input['city'],
                            'phone' => $input['phone'],
                            'appName' => $input['appName'],
                            'house_price' => $input['price'] ? $input['price'] : 0,
                            'house_room' => $input['house_room'] ? $input['house_room'] : 0,
                            'house_totalarea' => $input['area'] ? $input['area'] : 0,
                            'house_city' => $input['city'],
                            'borough_name' => $item,
                            'borough_id' => $borough_id_arr[$key],
                            'cityarea2_name' => '',
                            'cityarea2_id' => 0,
                            'admin_id' => session('dmp_user')['id'],
                            'admin_name' => session('dmp_user')['name']
                        ];
                        array_push($tourist_action_input, $aa);
                    }
                }
                if (count($cityarea2_arr)) {
                    foreach ($cityarea2_arr as $key => $item) {
                        $aa = [
                            'user_id' => $id,
                            'id' => Uuid::generate()->string,
                            'data_input' => 2,
                            'house_city' => $input['city'],
                            'phone' => $input['phone'],
                            'appName' => $input['appName'],
                            'house_price' => $input['price'] ? $input['price'] : 0,
                            'house_room' => $input['house_room'] ? $input['house_room'] : 0,
                            'house_totalarea' => $input['area'] ? $input['area'] : 0,
                            'house_city' => $input['city'],
                            'borough_name' => '',
                            'borough_id' => 0,
                            'cityarea2_name' => $item,
                            'cityarea2_id' => $cityarea2_id_arr[$key],
                            'admin_id' => session('dmp_user')['id'],
                            'admin_name' => session('dmp_user')['name']
                        ];
                        array_push($tourist_action_input, $aa);
                    }
                }
            }
            $re_action = false;
            if (count($tourist_action_input)) {
                $action_ins = new TouristAction();
                $action_ins->setTable('tourists_actions' . $this->getTableNum($old_data['phone']));
                $re_action = $action_ins->createBatch($tourist_action_input);
                if($re_action) {
                    $id_arr = [];
                    foreach ($tourist_action_input as $item){
                        array_push($id_arr,$item['id']);
                    }
                    event(new AdminEvent('add_tourist_action', $id_arr));
                }
            }
            if (count($tourist_info_input)) {
                $t_i = new TouristInfo();
                $one = $t_i->findOneByPhone($input['phone']);
                if ($one) {
                    $t_i->updateOneById($one['id'], $tourist_info_input);
                }
            }
            $re = (new Tourist())->updateOneById($id, $tourist_input);
            if ($re) {
                event(new AdminEvent('edit_tourist', $tourist_input, $old_data));
                return redirect($referer);
//                $redirect_url = $re_action ? 'admin/tourist/' . $id.'#action' : 'admin/tourist/' . $id;
//                return redirect($redirect_url)->with('errors', $re_action ? Config::get('admin.success.updateTourist') : Config::get('admin.success.update'));
            } else {
                return back()->with('errors', Config::get('admin.errors.editFail'));
            }
        }
        else{
            return back()->withErrors($validator);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if($id){
            $arr = explode('$',$id);
            $t_a = new TouristAction();
            $t_a->setTable('tourists_actions' . $this->getTableNum($arr[1]));
            $old_obj = $t_a->findOneById($arr[0]);
            $rs = $t_a->updateOneById($arr[0],['is_del' => 0]);
            if($rs){
                event(new AdminEvent('remove_tourist_action', $old_obj, ''));
                return back()->with('errors', Config::get('admin.success.operate'));
            }
        }
    }


    /*
     *  @method profile   save user profile
     *
     *  @param
     *      phone               string    手机号  必填
     *      name                string    名称
     *      business_area       string    商圈名称   逗号分隔多个
     *      business_area_ids   string    商圈id     逗号分隔多个
     *      district            string    小区名称   逗号分隔多个
     *      district_ids        string    小区id     逗号分隔多个
     *      house_room          string    居室
     *      price               string    价格
     *      area                string    面积
     *      remark              string    备注
     * */

    public function profile(Request $request){
        $input = $request->all();
        $t_p = new TouristProfile();
        if(!isset($input['phone'])){
            return $this->apiMessage(false, Config::get('admin.errors.phoneNeed'));
        }
        $one = $t_p->findOneByPhone($input['phone']);
        $rs = 0;
        if($one){
            $rs = $t_p->updateOneById($one['id'],$input);
        }
        else{
            $rs = $t_p->createNew($input);
        }
        if($rs){
            return $this->apiMessage(true, Config::get('admin.success.touristprofileSuccess'));
        }
        else{
            return $this->apiMessage(false, Config::get('admin.errors.touristprofileFail'));
        }
    }
}
